import React, { useState } from 'react';

import { Form, Input, Modal,Space,Button,Image } from 'antd';
import { String } from 'lodash';
import {  Select, Upload,message } from 'antd';
import { LoadingOutlined, PlusOutlined,MinusCircleOutlined   } from '@ant-design/icons';
const { Option } = Select;
const FormItem = Form.Item;

import styles from '../index.less';



export interface TabsFormProps {
    modalVisible: boolean;
    attrlist:API.SysDeviceAttrItem[];
    values?: any;
    onSubmit: (values: String) => void;
    onCancel: () => void;
  }
  
const formLayout = {
  labelCol: { span: 5 },
  wrapperCol: { span: 15 },
};

const formItemLayout = {
  labelCol: { span: 0 },
  wrapperCol: { span: 24 },
};

var fieldList=[{abb:'11',filed:'',browseName:''}];
  
const SelectAttr: React.FC<TabsFormProps> = (props) => {
 
 
    const { modalVisible, onSubmit: handleAdd, onCancel,attrlist } = props;
    const [formVals, setFormVals] = useState(props.values);
    const [loading, setLoading] = useState<boolean>(false);
    const [attrId, setAttrId] = useState<number>(null);
    const [form] = Form.useForm();

    const okHandle = async () => {
        const fieldsValue = await form.validateFields();
        fieldsValue.i=formVals.i;
        fieldsValue.picCode=formVals.picCode;
        handleAdd(fieldsValue);
    }
      
    const beforeUpload = (file: any) => {
      const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
      if (!isJpgOrPng) {
        message.error('只能上传JPG/PNG文件!');
      }
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        message.error('图像必须小于2MB!');
      }
      return isJpgOrPng && isLt2M;
    }
      
    const uploadButton = (
      <div>
        {loading ? <LoadingOutlined /> : <PlusOutlined />}
        <div className="ant-upload-text">上传图标</div>
      </div>
    );

    const handleChange = (info: any) => {
      if (info.file.status === 'uploading') {
        setLoading(true);
        return;
      }
      if (info.file.status === 'done') {
        const picCode = info.file.response.attachCode;
        console.log(picCode);
        setFormVals({ ...formVals, ...{ picCode: picCode } });
        setLoading(false);
      }
    };
    

    const changePic = async (value) =>  
    {
      form.setFieldsValue({"picCode":value})
      setFormVals({ ...formVals, ...{ picCode: value}  });
    }


    const changeFiled = async (value,options) =>  
    {
      form.setFieldsValue({"unit":attrlist[options.key].unit})
      form.setFieldsValue({"picCode":attrlist[options.key].attrImg})
      form.setFieldsValue({"text":attrlist[options.key].browseName})
      setAttrId(attrlist[options.key].attrId);
      setFormVals({ ...formVals, ...{ picCode: attrlist[options.key].attrImg}  });
    }


    const changeFileds = async (val,options,index) =>  
      {
      
        let value=options.key;
        let  filedsvalue= form.getFieldValue("fileds");
        let newValue=[...filedsvalue];
        // newValue[index].filed=attrlist[value].dispalyName;
        newValue[index].browseName=attrlist[value].browseName;

        let  unit= form.getFieldValue("unit");
        let  picCode= form.getFieldValue("picCode");
        if(attrId==null){
          setAttrId(attrlist[value].attrId);
        }
        if(unit==null||unit==""){
          form.setFieldsValue({"unit":attrlist[value].unit})
        }
        if(picCode==null||picCode==""){
          setFormVals({ ...formVals, ...{ picCode: attrlist[value].attrImg}  });
          form.setFieldsValue({"picCode":attrlist[value].attrImg})
        }
        form.setFieldsValue({"fileds":newValue})
      }
        
    return (
        <Modal
          width={640}
          maskClosable={false}
          destroyOnClose
          title="新增内容模块"
          visible={modalVisible}
          onOk={okHandle}
          onCancel={() => onCancel()}
        >
          <Form
            {...formLayout}
            initialValues={formVals}
            form={form}
          >
            <FormItem name="key" hidden={true}  >
                <Input  />
            </FormItem>
            <FormItem
            label="选择字段"
            hidden={ formVals.key==1?true:false}
          >
          <Form.List  name="fileds">
            {(fields, { add, remove }) => (
              <>
                {fields.map(field => (
                  <Space style={{ display: 'flex', marginBottom: 8 }}     key={field.key} align="baseline">
                  
                    <Form.Item
                      {...field}
                      {...formItemLayout}
                      style={{ flex:2}}
                      name={[field.name, 'filed']}
                      fieldKey={[field.fieldKey, 'filed']}
                      rules={[{ required: true, message: '请选择字段' }]}
                    >
                      <Select placeholder="请选择"  onChange={(value,option)=>changeFileds(value,option,field.fieldKey)}>
                        {attrlist.map((item,index) => (
                          <Option  key={index} value={item.dispalyName}>
                            {item.browseName}
                          </Option>
                      ))}
                      </Select>
                    </Form.Item>   
                    <Form.Item
                      {...field}
                      {...formItemLayout}
                      style={{ flex:1}}
                      name={[field.name, 'abb']}
                      fieldKey={[field.fieldKey, 'abb']}
                      rules={[{ required: true, message: '请输入简称' }]}
                    >
                       <Input placeholder="请输入简称" />
                    </Form.Item>
                    <Form.Item
                      name={[field.name, 'browseName']}
                      fieldKey={[field.fieldKey, 'browseName']}
                      hidden={true}
                    >
                        <Input  />
                    </Form.Item>
                    
                    {field.fieldKey>=1?
                    <MinusCircleOutlined onClick={() => remove(field.name)} />
                    :<></>
                    }
                  
                  </Space>
                ))}
                    <Button  type="dashed" onClick={() => add()} block icon={<PlusOutlined />}>
                    添加字段
                    </Button>
             
                
              </>
            )}
          </Form.List>
          </FormItem>
            <FormItem
                label="选择字段"
                name="filed"
                hidden={ formVals.key!=1?true:false}
                rules={[ formVals.key==1? { required: true}:{}]}
                >
                <Select placeholder="请选择"   onChange={changeFiled} >
                    {attrlist.map((item,index) => (
                      <Option key={index} value={item.dispalyName}>
                        {item.browseName}
                      </Option>
                ))}
                  </Select>
            </FormItem>

        <FormItem
          label="图标"
          name="picCode"
          rules={[{ required: true, message: '请上传图标'}]}
        >
           <Upload
                name="file"
                listType="picture-card"
                showUploadList={false}
                  className={styles.uploader}
               // headers={{ 'x-auth-token': getToken() }}
                data={{type:'attr',id:attrId}}
                action="/api/imageUpload"
                beforeUpload={beforeUpload}
                onChange={handleChange}
              >
                {formVals?.picCode ? <img src={'/img/'  + formVals?.picCode} alt="avatar" style={{ width: '100%' }} /> : uploadButton}
              </Upload>
              <div className={styles.selectImg}>
                <Image.PreviewGroup>
                {attrlist.map((item,index) => (
                        item?.attrImg?<Image width={40} preview={false} height={40}  src={'/img/'  + item?.attrImg} onClick={()=>changePic(item?.attrImg)} />: null
                  ))}
                </Image.PreviewGroup>
              </div>
        </FormItem>

 
        <FormItem
            label="栏目名称"
            name="text"
            rules={[{ required: true}]}
          >
          <Input placeholder="请输入" autoComplete='off' />
        </FormItem>
        <FormItem
            label="单位"
            name="unit"
            rules={[{ required: true}]}
          >
          <Input placeholder="请输入" autoComplete='off' />
        </FormItem>
       
     
          </Form>
        </Modal>
      );
};

export default SelectAttr;